<!-- Used by media_stat_perf to calculate <video> performance statistics. -->

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>CPU, Memory, and FPS Perf Test</title>
  </head>
  <body>
    <div id="log">
      Decoded frames: 0 Avg: 0<br>
      Dropped frames: 0 Avg: 0<br>
    </div>
    <video preload controls></video>
  </body>

  <script type="text/javascript">
    var video = document.querySelector("video");

    function calculateStats() {
      if (video.readyState <= HTMLMediaElement.HAVE_CURRENT_DATA ||
          video.paused || video.ended)
        return;
      // Not all test files have same duration, so to make the tests run shorter
      // we need a time limit.
      // From aggregated data, 5 seconds is enough time to get reliable results.
      if (video.currentTime > 5) {
        video.currentTime = video.duration;
      }

      currentTime = new Date().getTime();
      deltaTime = (currentTime - startTime) / 1000;
      startTime = currentTime;

      // Calculate decoded frames per sec.
      var fps = (video.webkitDecodedFrameCount - decodedFrames) / deltaTime;
      decodedFrames = video.webkitDecodedFrameCount;
      decodedFPS.push(fps);

      // Calculate dropped frames per sec.
      fps = (video.webkitDroppedFrameCount - droppedFrames) / deltaTime;
      droppedFrames = video.webkitDroppedFrameCount;
      droppedFPS.push(fps);

      var d = document.getElementById("log");
      d.innerHTML =
        "Decoded frames: " + decodedFrames +
        " Avg: " + decodedFPS + " fps.<br>" +
        "Dropped frames: " + droppedFrames +
        " Avg: " + droppedFPS + " fps.<br>";
    }

    video.addEventListener("playing", function(event) {
      decodedFrames = 0;
      droppedFrames = 0;
      decodedFPS = [];
      droppedFPS = [];
      startTime = new Date().getTime();
      intID = window.setInterval(calculateStats, 1000);
    });

    video.addEventListener("error", function() { endTest(false); }, false);
    video.addEventListener("ended", function() { endTest(true); }, false);

    function endTest(successFlag) {
      window.clearInterval(intID);
      // Notify PyAuto that we've completed the test run.
      if (window.domAutomationController)
        window.domAutomationController.send(successFlag);
    }

    function startTest(url) {
      video.src = url;
      video.play();
    }
  </script>
</html>
